<template>
  <div class="">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
        <el-alert
          title="只能允许修改第三级分类的数据"
          show-icon
          :closable=false
          type="warning">
        </el-alert>
        <el-row class="select_cate">
          <el-col>
            选择商品分类
            <!-- 级联选择框  v-model获取到选中的值 :options是数据源-->
            <el-cascader
            v-model="selectValue"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"></el-cascader>
          </el-col>
        </el-row>
        <!-- 标签页Tab -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button :disabled="isBtnDisabled" @click="cateVisible = true" type="primary">添加参数</el-button>
            <!-- 动态参数 -->
            <el-table :data="manyTableData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="handleClose(index,scope.row)" closable class="attr_vals" type="primary" v-for="(item, index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 确定按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" @click="showEditDialog(scope.row)" icon="el-icon-edit">修改</el-button>
                  <el-button type="danger" @click="removeInfoById(scope.row)" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button :disabled="isBtnDisabled" @click="cateVisible = true" type="primary">添加属性</el-button>
            <!-- 静态属性 -->
            <el-table :data="onlyTableData" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="handleClose(index,scope.row)" closable class="attr_vals" type="primary" v-for="(item, index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
                  <!-- 输入文本框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 确定按钮 -->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" @click="showEditDialog(scope.row)" icon="el-icon-edit">修改</el-button>
                  <el-button type="danger" @click="removeInfoById(scope.row)" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <!-- 添加参数/属性 -->
        <el-dialog
          :title="'添加'+textJust"
          :visible.sync="cateVisible"
          @close="closeClearData"
          width="70%">
          <span>添加{{textJust}}</span>
          <!-- 添加分类的表单 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item :label="textJust" prop="attr_name">
              <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cateVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 修改参数/属性 -->
        <el-dialog
          :title="'修改'+textJust"
          :visible.sync="editcateVisible"
          @close="closeEditClearData"
          width="70%">
          <span>修改{{textJust}}</span>
          <!-- 添加分类的表单 -->
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item :label="textJust" prop="attr_name">
              <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editcateVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
          </span>
        </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  components: {},
  data() {
    return {
      // 这里是分类的列表
      cateList: [],
      // 级联选择框选中的值 里面存放多个ID所以是一个数组
      selectValue: [],
      // 级联选择框的配置
      cateProps: {
        expandTrigger: 'hover',
        // 选择框要保存的值，这里指定ID
        value: 'cat_id',
        // 选择框名字
        label: 'cat_name',
        // 选择框下一级的的对象
        children: 'children'
      },
      // 当前选中的Tab 的名字
      // name是自己定义的
      activeName: 'many',
      // 存放动态属性的数据
      manyTableData: [],
      // 存放静态属性的数据
      onlyTableData: [],
      // 控制添加对话框的显示
      cateVisible: false,
      // 添加对象
      addForm: {
        // 属性名称
        attr_name: ''
      },
      // 添加表单的规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入合法的参数名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 控制修改对话框的显示
      editcateVisible: false,
      // 添加对象
      editForm: {
        // 属性名称
        attr_name: ''
      },
      // 添加表单的规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入合法的参数名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 控制按钮的禁用和使用
    isBtnDisabled() {
      if (this.selectValue.length !== 3) {
        return true
      }
      return false
    },
    // 获取第三级的ID
    getCatId() {
      if (this.selectValue.length === 3) {
        return this.selectValue[2]
      }
      return null
    },
    // 动态判断是添加静态属性还是 动态参数
    textJust() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  mounted() {
    // 获取商品的分类
    this.getCateList()
  },
  methods: {
    // 获取商品分类
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      // 赋值给获取到的 分类列表
      this.cateList = res.data
    },
    // 级联选择框发生改变触发的事件
    async handleChange() {
      // 查询数据
      this.getParamsData()
    },
    // Tab标签页的选中事件
    handleClick() {
      // 查询数据
      this.getParamsData()
    },
    // 获取数据
    async getParamsData() {
      // 控制级联选择器的范围 判断是否选择了三级分类
      if (this.selectValue.length !== 3) {
        this.selectValue = []
        // 清空数据
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 这里表示已经选择了三级分类
      // console.log(this.selectValue)
      // 发起请求
      const { data: res } = await this.$http.get(`categories/${this.getCatId}/attributes`, {
        params:
        {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res)
      // 先对attr_vals把 字符串变成数组
      res.data.forEach(item => {
        item.attr_vals = (item.attr_vals !== '') ? item.attr_vals.split(',') : []
        // 可编辑的Tag判断是否显示input
        item.inputVisible = false
        // 文本输入的内容
        item.inputValue = ''
        // console.log(item)
      })
      // console.log(res.data)
      // 判断是否是动态参数 还是静态属性
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭添加对话框
    closeClearData() {
      // 恢复初始的状态
      this.$refs.addFormRef.resetFields()
      this.cateVisible = false
      // console.log(111)
    },
    // 添加参数的方法
    addParams() {
      this.$refs.addFormRef.validate(async val => {
        const { data: res } = await this.$http.post(`/categories/${this.getCatId}/attributes`, {
          'attr_sel': this.activeName,
          'attr_name': this.addForm.attr_name
        })
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 关闭对话框
        this.cateVisible = false
        // 重新获取数据
        this.getParamsData()
      })
    },
    // 显示修改对话框
    showEditDialog(item) {
      this.editForm = item
      this.editcateVisible = true
    },
    // 关闭添加对话框
    closeEditClearData() {
      // 恢复初始的状态
      this.$refs.editFormRef.resetFields()
      this.editcateVisible = false
      // console.log(111)
    },
    // 点击按钮修改参数
    editParams() {
      this.$refs.editFormRef.validate(async val => {
        const { data: res } = await this.$http.put(`categories/${this.getCatId}/attributes/${this.editForm.attr_id}`, {
          'attr_sel': this.activeName,
          'attr_name': this.editForm.attr_name
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 关闭对话框
        this.editcateVisible = false
        // 重新获取数据
        this.getParamsData()
      })
    },
    // 删除信息
    async removeInfoById(role) {
      // role是传过来的 每一个角色 ,id 是当前所要删除权限的id
      // 该对话框 返回的一个字符串 promise对象
      const resStr = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 判断是否确定删除
      if (resStr !== 'confirm') return this.$message.info('用户取消操作')
      const { data: res } = await this.$http.delete(`categories/${this.getCatId}/attributes/${role.attr_id}`)
      // 修改失败就阻止
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 重新获取数据
      this.getParamsData()
    },
    // 文本框失去焦点 或者 抬起触发
    handleInputConfirm(item) {
      // 先判断输入框的内容是否为空
      if (item.inputValue.trim().length === 0) {
        // 清空输入框
        item.inputValue = ''
        // 隐藏输入框
        item.inputVisible = false
        return
      }
      // 不为空进行后续操作
      // 添加tag 到attr_vals中
      item.attr_vals.push(item.inputValue.trim())
      // 清空输入框
      item.inputValue = ''
      // 隐藏输入框
      item.inputVisible = false
      this.savaParams(item)
      // console.log(res.data)
    },
    // 按钮的点击
    showInput(item) {
      item.inputVisible = true
      // 文本框自动获取焦点
      // nextTick渲染参数完毕后自动调用回调
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 发起更改请求
    async savaParams(item) {
      // 发起请求
      const { data: res } = await this.$http.put(`categories/${this.getCatId}/attributes/${item.attr_id}`, {
        'attr_name': item.attr_name,
        'attr_sel': item.attr_sel,
        'attr_vals': item.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      item = res.data
    },
    // 监听Tag删除事件
    handleClose(index, row) {
      // 删除当前这项
      row.attr_vals.splice(index, 1)
      this.savaParams(row)
    }
  }
}
</script>
<style lang="less" scoped>
.select_cate{
  margin-top: 15px;
}
.attr_vals{
  margin: 15px;
}
.input-new-tag{
  width: 120px;
}
</style>
